package top.codef.secure.cloud.config;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.context.annotation.Bean;

import feign.RequestInterceptor;
import top.codef.crypt.aes.AESUtils;
import top.codef.crypt.aes.AesAlgorithm;
import top.codef.secure.properties.CerberusCodefCloudProperties;

public class CodefCloudSecureConfig {

	private final static String HEADER_NONCE = "x-codef-nonce";

	private final static String HEADER_TIMESTAMP = "x-codef-timestamp";

	private final static String HEADER_ACCESS_ID = "x-codef-access-id";

	private final static String HEADER_AUTHENTICATION = "x-codef-authentication";

	private final static String HEADER_TENANTID_NAME = "tenantId";

	@Bean
	RequestInterceptor secureIntercepor(CerberusCodefCloudProperties cerberusCodefCloudProperties) {
		return (template) -> {
			String nonce = RandomStringUtils.random(16, true, true);
			String timestamp = String.valueOf(System.currentTimeMillis());
			String bodyMd5 = DigestUtils.md5Hex(template.body() == null ? new byte[0] : template.body());
			String authentication = AESUtils.encrypt(AesAlgorithm.AES_GCM_NOPADDING, bodyMd5.getBytes(),
					cerberusCodefCloudProperties.getAccessSecret().getBytes(), nonce.getBytes(), timestamp.getBytes());
			template.header(HEADER_NONCE, nonce).header(HEADER_TIMESTAMP, timestamp)
					.header(HEADER_ACCESS_ID, cerberusCodefCloudProperties.getAccessId())
					.header(HEADER_AUTHENTICATION, authentication)
					.header(HEADER_TENANTID_NAME, cerberusCodefCloudProperties.getTenantId());
		};
	}

}
